import React, { memo, useEffect, useState } from "react";

import style from "./sty.module.css";
import { useHistory } from "react-router-dom";
import Scroll from "@/components/scroll";
import { reqTopList } from "../../api/topList";

const TopList = () => {
  const history = useHistory();
  const [topList, setTopList] = useState([]);
  const [topList2, setTopList2] = useState([]);
  const [isRefresh, setIsRefresh] = useState(false);
  useEffect(() => {
    reqTopList().then((res) => {
      const list = res.list || [];
      setTopList(list.slice(0, 4));
      setTopList2(list.slice(4));
    });
  }, []);
  const goDetail = (id) => {
    history.push(`/sheet/${id}?isTop=1`);
  };
  const imgLoad = (i) => {
    if (i === topList2.length - 1) {
      console.log("last");
      setIsRefresh(true);
    }
  };
  return (
    <Scroll cname={style.root} isRefresh={isRefresh}>
      <ul>
        {topList &&
          topList.map((item) => {
            return (
              <li
                key={item.id}
                className={style["top-item"]}
                onClick={() => goDetail(item.id)}
              >
                <img src={item.coverImgUrl} alt="" />
                <div className={style["top-info"]}>
                  <div className={style.name}>{item.name}</div>
                  <div className={style.list}>
                    {item.tracks &&
                      item.tracks.map((song, index) => (
                        <p key={song.first}>
                          {index + 1}.{song.first}- {song.second}
                        </p>
                      ))}
                  </div>
                </div>
              </li>
            );
          })}
      </ul>
      <ul className={style.content}>
        {topList2 &&
          topList2.map((item, i) => {
            return (
              <li
                key={item.id}
                className={style["top2-item"]}
                onClick={() => goDetail(item.id)}
              >
                <img src={item.coverImgUrl} onLoad={() => imgLoad(i)} alt="" />
                <div className={style["top2-item-info"]}>{item.name}</div>
              </li>
            );
          })}
      </ul>
    </Scroll>
  );
};

export default memo(TopList);
